<?php

namespace lico\Tool;

use lico\Runtime\Config;

use lico\Container;

class Session
{

    protected static $handler;
    protected static $config;
    protected static $type;

    public function __construct()
    {
        self::$config = Container::getBowl('lico\Runtime\Config')->app('session');
        $savePath = strtr(self::$config['savePath'], '//', DS);
        self::$config['savePath'] = ROOT_PATH . ltrim($savePath, DS);
        // d(file_exists(self::$config['savePath']));
        self::start();
        if (!session_id()) {
            session_start();
        }
        return true;
    }

    /**
     * 获取
     */
    public function get($name = "")
    {
        if ($name) {
            return isset($_SESSION[$name]) ? $_SESSION[$name] : [];
        } else {
            return $_SESSION;
        }
    }

    /**
     * 设置
     */
    public function set($key, $val)
    {
        return $_SESSION[$key] = $val;
    }

    /**
     * session
     */
    protected static function start()
    {

        $type = self::$config['type'];
        if ($type != self::$type) {
            ini_set('session.save_hadler', 'user');
            ini_set('session.save_path', self::$config['savePath']);
            ini_set('session.cookie_lifetime', self::$config['expire']); //客户端Cookie储存的时间
            ini_set('session.gc_maxlifetime', self::$config['expire']); //服务器端储存的时间
            ini_set('session.cookie_domain', self::$config['domain']);

            $className = ucfirst(strtolower($type));
            $class = __CLASS__ . '\\' . $className;
            self::$handler = new $class();
            self::$handler->config = self::$config;
            session_set_save_handler(self::$handler, true);
            self::$type = $type;
        }
        return self::$handler;
    }
}
